<?php

namespace App\Http\Controllers\Api\V1;

use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use App\Models\Course;
use App\Models\CourseUser;
use App\Models\CoursePayLog;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;

class PayController extends BasePayController
{
   public function __construct() {
	   parent::__construct();
   }

   public function wx_add(Request $request)
   {
	   $order = [
	       'out_trade_no' => time(),
	       'body' => 'subject-测试',
	       'total_fee' => '1',// **单位：分**
	   ];
	   return Pay::wechat($this->wxPayConfig)->wap($order);

	   // $pay->appId
	   // $pay->timeStamp
	   // $pay->nonceStr
	   // $pay->package
	   // $pay->signType
   }

   public function wx_notify()
   {
	   $pay = Pay::wechat($this->payConfig);

	   try{
		   $data = $pay->verify(); // 是的，验签就这么简单！

		   Log::debug('Wechat notify', $data->all());
	   } catch (\Exception $e) {
		   // $e->getMessage();
	   }
	   
	   // return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
	   return $pay->success();
   }
   
   public function ali_add(Request $request)
   {
   	   $order = [
   	       'out_trade_no' => time(),
   	       'body' => 'subject-测试',
   	       'total_fee' => '1',// **单位：分**
   	   ];
   	   return Pay::alipay($this->aliPayConfig)->scan($order);
   }
   
   public function ali_return()
   {
	   $data = Pay::alipay($this->aliPayConfig)->verify(); // 是的，验签就这么简单！

	   // 订单号：$data->out_trade_no
	   // 支付宝交易号：$data->trade_no
	   // 订单总金额：$data->total_amount
   }
   
   public function ali_notify()
   {
   	   $pay = Pay::alipay($this->aliPayConfig);
   
   	   try{
   		   $data = $pay->verify(); // 是的，验签就这么简单！
   
   		   Log::debug('alipay notify', $data->all());
   	   } catch (\Exception $e) {
   		   // $e->getMessage();
   	   }
   	   // return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
   	   return $pay->success();
   }
   
   /**
	* 发起支付
	* 1、暂时只支持 alipay
	*/
   public function xorpay_add(Request $request){
	   $regId = $request->get('reg_id', 0);
	   $payType = $request->get('pay_type', 'native');
	   $cuser = CourseUser::where('id', $regId)->first();
	   if(!$cuser){
			$this->returnFail('无效的学习登记，请重新登记');
	   }
	   if($payType == 'undefined'){
	        $payType = 'native';
	   }
	   // $payType = 'alipay';
	   //查看是否已有可用的支付
	   $existsOrder = $this->query_pay_log($regId, 'xorpay_'.$payType);
	   if($existsOrder){
		   return $this->returnSuccess($existsOrder);
	   }
	   
	   $payId = $this->add_pay_log($regId, 'xorpay_'.$payType);
	   if(!$payId){
		   $this->returnFail('创建支付订单失败');
	   }
	   
	   $course = Course::where('id', $cuser['course_id'])->first();
	   $resultPay = $this->xorpay_request([
				   'name' => $course['name'].'的学习费用',
				   'price' => $course['need_money'],
				   'order_id' => $payId,
				   'order_uid' => $cuser['account'],
				   'notify_url' => 'http://'. env('API_DOMAIN').'/api/pay/xorpay_notify', //回调路由
			   ], $payType);	   
			   
		\Log::debug('xorpay_add return: '.var_export($resultPay, true));
		
		$resultPay = object_to_array($resultPay);
		
		$upMore = [];
		//https://xorpay.com/doc/alipay.html
		$qr = '';
		if($resultPay && is_array($resultPay)){
			if($resultPay['status'] == 'ok'){
				if($resultPay['info']){
					$qr = $resultPay['info']['qr'];
					$upMore['qr'] = $qr;
				}
			}else{
				$this->update_pay_log($payId, 3, '', '', 0, $resultPay);
				return $this->returnFail($resultPay);
			}
		}
		
		$upRet = $this->update_pay_log($payId, 0, $resultPay['aoid'], '', $resultPay['expires_in'], $upMore);
		if(!$upRet){
			$this->returnFail('记录支付订单信息失败');
		}
		$retArr = [
			'qr' => $qr,
			'pay_type' => $payType,
			'ali_appid' => env('ALIPAY_APPID'),
		];
		return $this->returnSuccess($retArr);
   }
   protected function xorpay_request($data, $pay_type = 'native'){
	   $aid = env('XORPAY_AID');
	   $app_secret = env('XORPAY_APP_SECRET');
	   
	   $base_string = data_get($data, 'name') . $pay_type . data_get($data, 'price') . data_get($data, 'order_id') . data_get($data, 'notify_url') . $app_secret;
	   data_set($data, 'sign', md5($base_string));
	   data_set($data, 'pay_type', $pay_type);
	   $posts = Arr::only((array) $data, ['name', 'price', 'order_id', 'order_uid', 'notify_url', 'sign', 'pay_type',]);
	   \Log::debug('xorpay_request posts: '.\var_export($posts, true));
	   $http = new Client();
	   $response = $http->post('https://xorpay.com/api/pay/' . $aid, [
	       'form_params' => $posts,
	   ]);
	   
	   return json_decode($response->getBody()->__toString());
   }
   
   /**
   	* 查询
   	* 
   	*/
   public function xorpay_query(Request $request){
   	   \Log::debug('xorpay_query ...');
   	   $aoid = $request->get('aoid');
	   
   }
   
   /**
	* 回调
	* 支付成功后回调
	*/
   public function xorpay_notify(Request $request){
		\Log::debug('xorpay_notify ...');
		$aoid = $request->get('aoid');
		$orderId = $request->get('order_id');
		$payPrice = $request->get('pay_price');
		$payTime = $request->get('pay_time');
		$more = $request->get('more');
		$detail = $request->get('detail');
		$sign = $request->get('sign');
		
		$app_secret = env('XORPAY_APP_SECRET');
		$signStr = $aoid.$orderId.$payPrice.$payTime.$app_secret;
		$newSign = md5($signStr);
		if($sign != $newSign){
			\Log::error('signStr '.$signStr.' need sign: '.$sign);
			return $this->response->error('签名失败', 500);
		}
		if($orderId && $detail){
			$detailArr = json_decode($detail, true);
			$upRet = $this->update_pay_log($orderId, 1, 0, $detailArr);
		}
		
		if($orderId){
			//说明支付成功，可以下发任务
			
			$payLog = CoursePayLog::where('id', $orderId)->first();
			if(empty($payLog)){
				return $this->response->error('not found payLog', 500);
			}
			$upInfo = [
				'is_payed' => 1,
			];
			$upRet = CourseUser::where('id', $payLog->reg_id)->update($upInfo);
			if($upRet){
				return $this->returnSuccess('ok');
			}
		}
		
		return $this->response->error('fail', 500);
		
	}
}
